package example.exam.Shopee;

public class Demo5 {
    /**
     * [["1","1","1","1","0"],
     * ["1","1","0","1","0"],
     * ["1","1","0","0","0"],
     * ["0","0","0","0","0"]]
     *
     * @param grid
     * @return
     */
    public int numIslands(String[][] grid) {
        int sum = 0;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if (grid[i][j].equals("1")) {
                    sum++;
                    dfs(grid, i, j);
                }
            }
        }
        return sum;
    }

    public void dfs(String[][] grid, int i, int j) {
        if (i >= grid.length || j >= grid[0].length || i < 0 || j < 0 || grid[i][j].equals("0")) {
            return;
        }
        grid[i][j] = "0";
        dfs(grid, i + 1, j);
        dfs(grid, i - 1, j);
        dfs(grid, i, j - 1);
        dfs(grid, i, j + 1);

    }

    public static void main(String[] args) {
        Demo5 demo5 = new Demo5();
//        int islands = demo5.numIslands(new String[][]{
//                {"1", "1", "1", "1", "0"},
//                {"1", "1", "0", "1", "0"},
//                {"1", "1", "0", "0", "0"},
//                {"0", "0", "0", "0", "0"}});
        int islands = demo5.numIslands(new String[][]{
                {"1", "1", "1", "1", "1"},
                {"1", "1", "1", "1", "1"},
                {"1", "1", "1", "1", "1"},
                {"1", "1", "1", "1", "1"}});
        System.out.println(islands);
    }
}
